package com.leyou.item.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.constants.LyConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.CategoryDto;
import com.leyou.item.entity.Category;
import com.leyou.item.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CategoryService extends ServiceImpl<CategoryMapper, Category> {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    public List<Category> findCategoryByPid(Long pid) {
        //封装条件[不推荐]
//        QueryWrapper<Category> wrapper = new QueryWrapper<>();
//        wrapper.eq("parentId", pid);

        //封装条件[不推荐]
//        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(Category::getParentId, pid);

        Category entity = new Category();
        entity.setParentId(pid);
        QueryWrapper<Category> wrapper = Wrappers.query(entity);
        //执行条件查询
        List<Category> categoryList = categoryMapper.selectList(wrapper);
        if(CollectionUtils.isEmpty(categoryList)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return categoryList;
    }

    public List<Category> findCategoriesByIds(List<Long> ids) {
        List<Category> categoryList = categoryMapper.selectBatchIds(ids);
        if(CollectionUtils.isEmpty(categoryList)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return categoryList;
    }

    public List<CategoryDto> findCategorySubclass(Long id) {
        String key = LyConstants.CATEGORY_Key+id;
        String categorys = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(categorys)){
            List<CategoryDto> categoryDtoList = JsonUtils.toList(categorys, CategoryDto.class);
            return categoryDtoList;
        }
        List<CategoryDto> categoryDtos = categoryMapper.findAll(id);
        if (CollectionUtils.isEmpty(categoryDtos)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        redisTemplate.opsForValue().set(key,JsonUtils.toString(categoryDtos));
        return categoryDtos;
    }
}
